package dryven.persistence;

import dryven.config.DatabaseConfiguration;
import dryven.config.DatabaseConfigurationSource;
import dryven.persistence.provider.PersistenceProvider;
import dryven.request.RequestLifeCycleListener;
import dryven.request.controller.ControllerDescription;
import dryven.request.controller.result.ActionResult;
import dryven.request.http.Request;

public class PersistenceInitializer implements RequestLifeCycleListener {

	private PersistenceProvider _provider;
	private DatabaseConfigurationSource _dbConfigs;
	
	public PersistenceInitializer(PersistenceProvider provider,
			DatabaseConfigurationSource dbConfigs) {
		super();
		_provider = provider;
		_dbConfigs = dbConfigs;
	}
	
	@Override
	public void beforeRouting(Request request) {
		if(_dbConfigs.getDatabaseConfigurations()!=null) {
			for (DatabaseConfiguration config : _dbConfigs.getDatabaseConfigurations()) {
				PersistenceConnection conn = new PersistenceConnection(_provider, config);
				request.setAttribute(PersistenceConnection.class.getName()+config.getConnectionName(), conn);
			}
		}
	}

	@Override
	public void endRequest(Request request) {
		if(_dbConfigs.getDatabaseConfigurations()!=null) {
			for (DatabaseConfiguration config : _dbConfigs.getDatabaseConfigurations()) {
				PersistenceConnection conn = (PersistenceConnection) request.getAttribute(EntityManagerUtil.getPersistenceConnectionStorageKey(config));
				if(conn!=null) {
					conn.cleanup();
				}
			}
		}
	}

	@Override
	public void startRequest(Request request, ControllerDescription cd) {}

	@Override
	public void startResult(Request request, ActionResult result) {}

	@Override
	public void endResult(Request request, ActionResult result) {}

	@Override
	public void shutdown() {
		for (DatabaseConfiguration config : _dbConfigs.getDatabaseConfigurations()) {
			_provider.cleanup(config);
		}
	}

}
